import cs from 'classnames'
import Head from 'next/head'
import Image from 'next/image'
import router from 'next/router'
import { useState } from 'react'

import { LoginRep } from '@/api/interface/entity'
import { Login } from '@/api/modules/entity'
import banner from '@/assets/images/banner.png'
import Account from '@/components/Entity/Account'
import SmsCode from '@/components/Entity/SmsCode'
import Header from '@/components/Header'
import Layout from '@/components/Layout'
import { DefaultPath } from '@/routes'
import store from '@/store'
import useLocale from '@/utils/useLocale'

import locale from './locale'
import styles from './style/index.module.less'
function Entity() {
  const t = useLocale(locale)
  const onSubmit = () => {
    setSetup(1)
  }

  const [formData, setFormData] = useState<LoginRep>({ username: '', mobile: '', code: '' })

  const onNext = (email: string, mobile: string, code: string) => {
    setFormData((a) => {
      return { ...a, username: email.trim(), mobile: mobile, code: code }
    })
    setSetup(2)
  }

  const onChange = (setup: number, code: string) => {
    setSetup(setup)
    if (setup === 2) {
      console.log(code)
      onLogin(formData.username, code)
    }
  }

  const onLogin = (username: string, password: string) => {
    Login({ username: username.trim(), password })
      .then((res) => {
        console.log(res.data)
        const { token, authorities } = res.data
        const roles = authorities.map((a: { authority: string }) => a.authority)
        store.dispatch({ type: 'update-token', payload: { token: token } })

        store.dispatch({
          type: 'update-userInfo',
          payload: {
            userInfo: { ...res.data, email: username, avatar: '' },
            authorities: roles,
          },
        })
        const defaultPath = DefaultPath(roles)
        console.log(defaultPath)
        router.push(defaultPath)
      })
      .catch(() => {})
  }

  const [setup, setSetup] = useState<number>(1)
  const FormComponents: { [key: number]: JSX.Element } = {
    1: <Account email={formData.username} onNext={onNext} />,
    2: (
      <SmsCode
        onChange={onChange}
        mobile={formData.mobile}
        email={formData.username}
        code={formData.code}
      />
    ),
  }

  return (
    <>
      <Head>
        <title>{t.title}</title>
      </Head>

      <div className={cs('w-full h-screen relative overflow-hidden flex items-center')}>
        <Header show={true} onSubmit={() => onSubmit()} />
        {setup === 1 ? (
          <Image className={cs('w-full h-auto ')} src={banner} alt="icon" priority />
        ) : (
          ''
        )}

        <div className={cs(styles['container'], setup === 1 ? styles['container-bg'] : '')}>
          <div className={styles['width']}>{FormComponents[setup]}</div>
        </div>
      </div>
    </>
  )
}

export default Entity

Entity.getLayout = function getLayout(page: React.ReactNode) {
  return <Layout>{page}</Layout>
}
